package com.zhang;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义realm
 * 1.继承AuthorizingRealm
 * 2.实现方法
 */
public class CustomRealm extends AuthorizingRealm{
    /**
     * 是用来做授权
     * @param principalCollection
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
    /**
     * 用来做认证的
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.从主体传过来的认证信息中，获得用户名
       String username=(String)authenticationToken.getPrincipal();

       //2.通过用户名到数据库获取凭证
        String password =getpasswordByUserName(username);
        if (password==null)
        {
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo("zhang","123","customRealm");

        return authenticationInfo;
    }

    /**
     * 去查数据库
     * @param username
     * @return
     */
//    模仿数据库
    Map<String,String> userMap=new HashMap<String, String>();
    {
        userMap.put("zhang","123");
        super.setName("customRealm");
    }
    private String getpasswordByUserName(String username) {
        return userMap.get(username);
    }
}
